package com.hs.projectback.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hs.projectback.exception.BusinessException;
import com.hs.projectback.mapper.UserMapper;
import com.hs.projectback.common.ErrorCode;
import com.hs.projectback.service.UserService;
import com.hs.projectback.model.domain.User;
import com.hs.projectback.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.hs.projectback.constant.UserConstant.*;

/**
 * @author 韩帅
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-02-06 13:30:11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /*
     * 盐值
     * */
    private static final String SALT = "hanshuai";


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1.校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        //账户不能包含特殊字符
        Matcher matcher = Pattern.compile(VALIDPATTERN).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号包含特殊字符");
        }
        // 密码和校验密码不相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码与校验密码不相同");
        }
        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户重复");
        }
        //星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        }
        //2. 加密
        final String SALT = "hanshuai";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "保存失败");
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "长度错误");
        }
        //账户不能包含特殊字符
        Matcher matcher = Pattern.compile(VALIDPATTERN).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号包含特殊字符");
        }
        //2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserAccount", userAccount);
        queryWrapper.eq("UserPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在");
        }
        //3.用户脱敏
        User safetyUser = getSafetyUser(user);

        //4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在");
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 用来提前建立数据库连接，防止后续的sql与内存方法的时间长短比较不正确
        userMapper.selectCount(null);

        //一 ：sql方法
        long startTime = System.currentTimeMillis();
        //拼接 and 查询
        //like '%java%' and like '%python%'
//        for (String tagName : tagNameList) {
//            queryWrapper = queryWrapper.like("tags", tagName);
//        }
//        List<User> userList = userMapper.selectList(queryWrapper);
//        log.info("sql query time = " + (System.currentTimeMillis() - startTime));

        //二 ：内存方法
        //1.先查询所有用户
        startTime = System.currentTimeMillis();
        queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //2.再内存中判断是否包含要求的标签
        /**
         *  list.stream().filter(user -> ).collect(Collectors.toList())
         *  功能类似于for循环，user为 list中的对象
         *  。collect()返回的是一个集合
         */

        userList = userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            if (StringUtils.isBlank(tagsStr)) {
                return false;
            }
            //Gson提供了fromJson()方法来实现从Json相关对象到Java实体的方法。
            //当前情况下 tagsStr 里面存放的是 json 对象，转换成Set<String>类型的数据
            // new TypeToken<Set<String>>(){}.getType()为Gson提供的类型转换器，把json对象转换为Set<String>类型
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
            // this::getSafetyUser 把处理完的user调用 getSafetyUser() 方法
            // .map()是 Stream 中 调用别的方法的函数
        }).map(this::getSafetyUser).collect(Collectors.toList());
        log.info("memory query time = " + (System.currentTimeMillis() - startTime));

        return userList;
    }

    @Override
    public int updateUser(User user, User loginUser) {
        long id = user.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果登录用户是管理员用户,允许更新任意用户
        //如果用户是普通用户，只能更新自己信息
        if (!isAdmin(loginUser) && id != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(id);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request) {
        //仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户权限不足");
        }
        return true;
    }

    /**
     * 是否为管理员(重载)
     *
     * @param user
     * @return
     */
    public boolean isAdmin(User user) {
        //仅管理员可查询
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户权限不足");
        }
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        return (User) userObj;
    }

    /**
     * 匹配用户
     *
     * @param num       匹配标签的限制数量
     * @param loginUser 当前登录的用户
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //只查询 id 和 tags 两列的信息出来，减少运行时间
        queryWrapper.select("id", "tags");
        //只查询 tags 不为空的行，减少运行时间
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        //获取当前用户的的标签信息
        String tempTags = loginUser.getTags();
        Gson gson = new Gson();
        //由于标签列是json格式的数据，所以先使用gson把json格式数据转换成List<String>
        List<String> userTags = gson.fromJson(tempTags, new TypeToken<List<String>>() {
        }.getType());
        //创建一个list，存放Pair对象，一个User对象,一个是long类型的距离算法值
        List<Pair<User, Long>> list = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            //获取数据库中其他用户的标签信息
            User user = userList.get(i);
            String tags = user.getTags();
            //剔除出无标签的用户和自己
            if (StringUtils.isBlank(tags) || user.getId() == loginUser.getId()) {
                continue;
            }
            // 有标签的用户
            List<String> otherUserTags = gson.fromJson(tags, new TypeToken<List<String>>() {
            }.getType());
            long distance = AlgorithmUtils.minDistance(userTags, otherUserTags);
            list.add(new Pair<>(user, distance));
        }
        //按编辑距离从小到大进行排序
        //list.stream() 对list中的数据进行流处理，即每条都处理，类似于for循环
        //sorted() 对 stream 流中的数据进行按规则排序(默认是升序排序)，若是 a - b 则代表从小到大排序（ 1 - 2 是升序 // 2 - 1 是降序）
        //limit(num) 对 stream 流中的数据进行抽取，只取前 num 个
        List<Pair<User, Long>> toUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 获取要返回的用户的id
        List<Long> userIdList = toUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //多值查询，即获取 id 属性列值为 userIdList 中元素的行
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        // User::getId 相当于用 User的对象.getId() 方法，无需创建对象就可调用方法
        // Collectors.groupingBy() 默认按升序排序，这里是把用户的 id 按升序排序
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        //userIdUserListMap 是存放userId 和user对象的map
        //.get(userId)获取userId 对应的List<User>对象
        //.get(0) 获取List中的 User 对象
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;


    }


}




